<script setup lang="ts">
import { HotTable } from '@handsontable/vue3';
import { registerAllModules } from 'handsontable/registry';
import { registerLanguageDictionary, zhCN } from 'handsontable/i18n';
import { nextTick, onMounted, ref, watch } from 'vue';
import 'handsontable/styles/handsontable.css';
import 'handsontable/styles/ht-theme-main.css';

registerAllModules();
registerLanguageDictionary(zhCN);

const props = defineProps({
  tableConfig: {
    type: Object,
    required: true,
    default: () => ({
      data: [
        ['', '']
      ],
      config: {
        mergedCells: [],
        cellStyles: [],
        columnWidths: [],
        colHeaders: ['Chapter/章', 'Goal/学习目标']
      }
    })
  },
  readOnly: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:tableConfig']);
const hotRef = ref<any>(null);
let observer: MutationObserver | null = null;
const hotSettings = ref({
  data: props.tableConfig.data || [
    ['', '']
  ],
  colHeaders: props.tableConfig.config.colHeaders || [],
  colWidths: props.tableConfig.config.columnWidths || [],
  height: 'auto',
  language: 'zh-CN',
  readOnly: props.readOnly,
  autoWrapRow: true,
  autoWrapCol: true,
  copyPaste: false,
  contextMenu: !props.readOnly,
  mergeCells: true,
  stretchH: 'all',
  manualColumnResize: !props.readOnly,
  width: '100%',
  // 禁用所有鼠标操作
  disableVisualSelection: props.readOnly,
  disableVisualSelectionForHeaders: props.readOnly,
  disableVisualSelectionForColumns: props.readOnly,
  disableVisualSelectionForRows: props.readOnly,
  // 禁用其他交互功能
  outsideClickDeselects: !props.readOnly,
  autoComplete: !props.readOnly,
  fillHandle: !props.readOnly,
  scrollbarV: !props.readOnly,
  // 启用表头编辑功能
  afterOnCellMouseDown: function(event: any, coords: any) {
    // 检查是否点击了表头
    if (coords.row < 0) {
      if (props.readOnly) {
        return;
      }
      const hot = this as any;
      const col = coords.col;
      
      // 创建输入框
      const input = document.createElement('input');
      input.type = 'text';
      input.value = (hot.getSettings().colHeaders?.[col] || '');
      input.style.position = 'absolute';
      input.style.zIndex = '10001';
      input.style.border = 'none';
      input.style.borderRadius = '0px';
      input.style.outline = '1px solid #0067D1';
      input.style.padding = '6px 10px';
      input.style.fontSize = '14px';
      input.style.fontWeight = 'normal';
      input.style.background = '#ffffff';
      input.style.boxShadow = 'none';
      input.style.margin = '0';
      input.style.fontFamily = 'inherit';
      
      // 定位输入框并设置宽高
      const headerCell = hot.getCell(coords.row, coords.col);
      const rect = headerCell.getBoundingClientRect();
      input.style.left = rect.left + 'px';
      input.style.top = rect.top + 'px';
      input.style.width = rect.width + 'px';
      input.style.height = rect.height + 'px';
      
      // 添加到页面
      document.body.appendChild(input);
      input.focus();
      input.select();
      
      // 处理输入完成
      const handleInputComplete = () => {
        const newValue = input.value.trim();
        const currentHeaders = hot.getSettings().colHeaders || [];
        const currentValue = currentHeaders[col] || '';

        if (newValue !== currentValue) {
          // 创建新的表头数组，避免直接修改原数组
          const newHeaders = [...currentHeaders];
          newHeaders[col] = newValue;

          // 更新 hotSettings 中的 colHeaders，确保重新渲染时使用最新值
          hotSettings.value.colHeaders = newHeaders;
          // 使用 updateSettings 方法设置表头，但不触发数据重载
          hot.updateSettings({
            colHeaders: newHeaders
          }, false); // 第二个参数为 false，避免重新渲染整个表格

          // 保存设置
          saveTableSettings();
        }
        if (document.body.contains(input)) {
          document.body.removeChild(input);
        }
      };
      
      // 监听事件
      input.addEventListener('blur', handleInputComplete);
      input.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
          handleInputComplete();
        } else if (e.key === 'Escape') {
          if (document.body.contains(input)) {
            document.body.removeChild(input);
          }
        }
      });
    }
  },
  // 设置第一行背景色
  cells: function(row: number, col: number, prop: string) {
    const cellProperties: any = {};
    
    // 第一行设置背景色
    if (row === 0) {
      cellProperties.style = {
        backgroundColor: '#f5f7fa'
      };
    }
    
    // 设置所有单元格的字体颜色
    cellProperties.style = {
      ...cellProperties.style,
      color: '#191919'
    };
    
    // 设置表头左对齐
    if (row < 0) {
      console.log('表头左对齐')
      console.log(cellProperties)
      cellProperties.style = {
        ...cellProperties.style,
        textAlign: 'left'
      };
    }
    
    return cellProperties;
  },
  licenseKey: 'non-commercial-and-evaluation',
  // 添加自定义回调来设置 z-index
  afterContextMenuShow: function(event: any) {
    setMenuZIndex();
  },
  // 确保在初始化后也设置 z-index
  afterInit: function() {
    setMenuZIndex();
    // 延迟加载设置，确保表格完全初始化
    setTimeout(() => {
      loadTableSettings();
    }, 100);
  },
  // 数据变化时保存设置
  afterChange: function(changes: any, source: any) {
    if (source !== 'loadData') {
      saveTableSettings();
    }
  },
  // 合并单元格变化时保存设置
  afterMergeCells: function(mergeRange: any, mergeParent: any) {
    saveTableSettings();
  },
  // 取消合并时保存设置
  afterUnmergeCells: function(mergeRange: any, mergeParent: any) {
    saveTableSettings();
  },
  // 行变化时保存设置
  afterCreateRow: function(index: number, amount: number, source: any) {
    saveTableSettings();
  },
  afterRemoveRow: function(index: number, amount: number, source: any) {
    saveTableSettings();
  },
  // 列变化时保存设置
  afterCreateCol: function(index: number, amount: number, source: any) {
    saveTableSettings();
  },
  afterRemoveCol: function(index: number, amount: number, source: any) {
    saveTableSettings();
  },
  // 单元格值变化时保存设置
  afterSetDataAtCell: function(changes: any, source: any) {
    if (source !== 'loadData') {
      saveTableSettings();
    }
  },
  // 单元格属性变化时保存设置
  afterSetCellMeta: function(row: any, col: any, key: any, value: any) {
    if (key === 'className') {
      saveTableSettings();
    }
  },
  // 行移动时保存设置
  afterRowMove: function(movedRows: any, finalIndex: number, dropIndex: number, dropOrder: any, orderChanged: boolean) {
    if (orderChanged) {
      saveTableSettings();
    }
  },
  // 列移动时保存设置
  afterColumnMove: function(movedColumns: any, finalIndex: number, dropIndex: number, dropOrder: any, orderChanged: boolean) {
    if (orderChanged) {
      saveTableSettings();
    }
  },
  // 行调整大小时保存设置
  afterRowResize: function(currentRow: number, newHeight: number, isDoubleClick: boolean) {
    saveTableSettings();
  },
  // 列调整大小时保存设置
  afterColumnResize: function(currentColumn: number, newWidth: number, isDoubleClick: boolean) {
    console.log(`列 ${currentColumn} 宽度调整为: ${newWidth}px`);
    saveTableSettings();
  }
})


// 保存表格设置
const saveTableSettings = () => {
  if (!hotRef.value?.hotInstance) return;
  
  const hot = hotRef.value.hotInstance;
  
  // 获取合并单元格信息
  const mergeCellsPlugin = hot.getPlugin('mergeCells');
  const mergedCells = mergeCellsPlugin?.mergedCellsCollection?.mergedCells || [];
  
  // 获取单元格样式信息
  const cellStyles: any[] = [];
  const data = hot.getData();
  const rows = data.length;
  const cols = data[0]?.length || 0;
  
  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < cols; col++) {
      const cellMeta = hot.getCellMeta(row, col);
      const cellStyle: any = {
        row,
        col
      };
      
      // 收集样式信息
      if (cellMeta.className) {
        cellStyle.className = cellMeta.className;
      }
      
      // 第一行背景色
      if (row === 0) {
        cellStyle.style = {
          ...cellStyle.style,
          backgroundColor: '#f5f7fa'
        };
      }
      
      // 所有单元格字体颜色
      cellStyle.style = {
        ...cellStyle.style,
        color: '#191919'
      };
      
      cellStyles.push(cellStyle);
    }
  }
  
  // 获取表格数据
  const tableData = hot.getData();
  
  // 获取列宽度信息
  const columnWidths: number[] = [];
  try {
    const colCount = hot.countCols();
    for (let i = 0; i < colCount; i++) {
      try {
        // 使用 getColWidth 方法获取列宽度
        const width = hot.getColWidth(i);
        columnWidths.push(width);
      } catch (error) {
        console.warn('获取列宽度失败:', i, error);
        columnWidths.push(100); // 默认宽度
      }
    }
  } catch (error) {
    console.warn('获取列数量失败:', error);
  }
  
  const config = {
    mergedCells: Array.from(mergedCells || []),
    cellStyles: cellStyles,
    columnWidths: columnWidths,
    colHeaders: hot.getSettings().colHeaders
  }
  
  // 通知父组件
  if (!props.readOnly) {
    console.log('更新 tableConfig:', {
      data: tableData,
      config: config
    });
    emit('update:tableConfig', {
      data: tableData,
      config: config
    });
  }
};

// 从 props 加载表格设置
const loadTableSettings = () => {
  if (props.readOnly) {
    console.log('readOnly')
    console.log(hotRef.value?.hotInstance)
  }
  if (!hotRef.value?.hotInstance) return;
  console.log('loadTableSettings')
  console.log(props.tableConfig)
  const savedSettings = props.tableConfig;
  if (!savedSettings || !savedSettings.config) {
    console.log('没有保存的设置或配置为空');
    return;
  }
  
  try {
    const settings = savedSettings;
    const hot = hotRef.value.hotInstance;

    // 只在只读模式下加载数据，避免编辑时的数据冲突
    if (props.readOnly && settings.data && settings.data.length > 0) {
      hot.loadData(settings.data);
    }
    
    // 恢复合并单元格
    if (settings.config.mergedCells) {
      try {
        const mergeCellsPlugin = hot.getPlugin('mergeCells');
        if (!mergeCellsPlugin) {
          console.warn('mergeCells 插件不可用，跳过合并单元格恢复');
          return;
        }
        
        console.log('恢复合并单元格:', settings.config.mergedCells);
        
        // 如果 mergedCells 为空数组，取消所有合并
        if (settings.config.mergedCells.length === 0) {
          console.log('取消所有单元格合并');
          // 获取当前所有合并的单元格
          const currentMergedCells = mergeCellsPlugin.mergedCellsCollection?.mergedCells || [];
          // 取消所有合并
          currentMergedCells.forEach((mergedCell: any) => {
            try {
              mergeCellsPlugin.unmerge(mergedCell.row, mergedCell.col);
            } catch (error) {
              console.warn('取消合并单元格失败:', mergedCell, error);
            }
          });
        } else {
          // 先取消所有现有合并
          const currentMergedCells = mergeCellsPlugin.mergedCellsCollection?.mergedCells || [];
          currentMergedCells.forEach((mergedCell: any) => {
            try {
              mergeCellsPlugin.unmerge(mergedCell.row, mergedCell.col);
            } catch (error) {
              console.warn('取消现有合并单元格失败:', mergedCell, error);
            }
          });
          
          // 然后应用新的合并设置
          settings.config.mergedCells.forEach((mergeInfo: any) => {
            try {
              mergeCellsPlugin.merge(mergeInfo.row, mergeInfo.col, mergeInfo.row + mergeInfo.rowspan - 1, mergeInfo.col + mergeInfo.colspan - 1);
            } catch (error) {
              console.warn('恢复合并单元格失败:', mergeInfo, error);
            }
          });
        }
      } catch (error) {
        console.warn('恢复合并单元格失败:', error);
      }
    }
    
    // 恢复单元格样式（对齐设置）
    if (settings.config.cellStyles && settings.config.cellStyles.length > 0) {
      console.log('恢复单元格样式:', settings.config.cellStyles);
      settings.config.cellStyles.forEach((style: any) => {
        try {
          hot.setCellMeta(style.row, style.col, 'className', style.className);
        } catch (error) {
          console.warn('恢复单元格样式失败:', style, error);
        }
      });
    }
    
    // 恢复列宽度设置
    if (settings.config.columnWidths && settings.config.columnWidths.length > 0) {
      console.log('恢复列宽度:', settings.config.columnWidths);
      try {
        // 使用 updateSettings 方法批量设置列宽度
        const colWidths: any = {};
        settings.config.columnWidths.forEach((width: number, index: number) => {
          colWidths[index] = width;
        });
        
        // 检查是否有有效的列宽度设置
        if (Object.keys(colWidths).length > 0) {
          hot.updateSettings({ colWidths });
        }
      } catch (error) {
        console.warn('恢复列宽度失败:', error);
      }
    }
    
    // 恢复表头设置
    if (settings.config.colHeaders && settings.config.colHeaders.length > 0) {
      console.log('恢复表头:', settings.config.colHeaders);
      try {
        // 更新 hotSettings 中的 colHeaders，确保重新渲染时使用最新值
        hotSettings.value.colHeaders = settings.config.colHeaders;
        
        // 使用 updateSettings 方法设置表头
        hot.updateSettings({ colHeaders: settings.config.colHeaders });
      } catch (error) {
        console.warn('恢复表头失败:', error);
      }
    }
    

    
    // 强制重新渲染
    hot.render();
    console.log('表格设置已恢复:', settings);
  } catch (error) {
    console.error('加载表格设置失败:', error);
  }
};

// 设置 z-index 的函数
const setMenuZIndex = () => {
  nextTick(() => {
    const menus = document.querySelectorAll('.htMenu');
    menus.forEach((menu: any) => {
      if (menu.style) {
        menu.style.zIndex = '10000';
        menu.style.borderRadius = '4px';
      }
    });
    
    // 特别处理 el-drawer 中的菜单
    const drawerMenus = document.querySelectorAll('.el-drawer__wrapper .htMenu, .el-drawer__container .htMenu');
    drawerMenus.forEach((menu: any) => {
      if (menu.style) {
        menu.style.zIndex = '10000';
        menu.style.borderRadius = '4px';
      }
    });
  });
};


// 监听 DOM 变化，确保新创建的菜单也有正确的 z-index
const setupMenuObserver = () => {
  observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.type === 'childList') {
        mutation.addedNodes.forEach((node: any) => {
          if (node.nodeType === Node.ELEMENT_NODE && node.classList?.contains('htMenu')) {
            if (node.style) {
              node.style.zIndex = '10000';
              node.style.borderRadius = '4px';
            }
          }
        });
      }
    });
  });

  observer.observe(document.body, {
    childList: true,
    subtree: true
  });
};

// 强制设置 z-index 的函数，用于紧急情况
const forceSetZIndex = () => {
  setTimeout(() => {
    const allMenus = document.querySelectorAll('.htMenu, .handsontable .htMenu, .el-drawer .htMenu');
    allMenus.forEach((menu: any) => {
      if (menu.style) {
        menu.style.zIndex = '10000';
        menu.style.position = 'fixed';
        menu.style.borderRadius = '4px';
      }
    });
  }, 100);
};

// 手动保存设置的方法
const manualSaveSettings = () => {
  saveTableSettings();
};

// 清除保存的设置
const clearSavedSettings = () => {
  localStorage.removeItem('handsontable_settings');
  console.log('已清除保存的表格设置');
};

// 导出设置方法供父组件使用
defineExpose({
  saveSettings: manualSaveSettings,
  clearSettings: clearSavedSettings,
});

// 组件挂载后设置观察器
onMounted(() => {
  setupMenuObserver();
  setMenuZIndex();
  // 延迟执行强制设置，确保在 drawer 完全加载后执行
  setTimeout(() => {
    forceSetZIndex();
  }, 500);
});

watch(() => props.tableConfig, (newConfig) => {
  if (newConfig && hotRef.value?.hotInstance && props.readOnly) {
    loadTableSettings();
  }
}, { deep: true });
</script>

<template>
  <div class="w-full">
    <hot-table :settings="hotSettings" ref="hotRef" :class="{ 'readonly': props.readOnly }" />
  </div>
</template>

<style lang="scss" scoped>
/* 确保 Handsontable 的 contextMenu 在 drawer 中正确显示 */
:deep(.htMenu.handsontable.htContextMenu) {
  z-index: 10000 !important;
}

:deep(.htMenu.handsontable.htContextMenu.htHasScrollY) {
  z-index: 10000 !important;
}

:deep(.htMenu.handsontable.htContextMenu.htHasScrollX) {
  z-index: 10000 !important;
}

/* 确保所有 Handsontable 菜单都有足够高的层级 */
:deep(.htMenu) {
  z-index: 10000 !important;
}

/* 针对 drawer 中的特殊情况 */
:deep(.el-drawer__wrapper .htMenu) {
  z-index: 10000 !important;
}

/* 确保 Handsontable 的弹出层在 drawer 之上 */
:deep(.handsontable .htMenu) {
  z-index: 10000 !important;
}

/* 针对 Element Plus drawer 的层级问题 */
:deep(.el-drawer__container .htMenu) {
  z-index: 10000 !important;
}

/* 表格边框颜色 */
:deep(.handsontable) {
  border-color: #DCDFE6 !important;
}

:deep(.handsontable .htCore) {
  border-color: #DCDFE6 !important;
}

/* 所有单元格边框 */
:deep(.handsontable .htCore th),
:deep(.handsontable .htCore td) {
  border-color: #DCDFE6 !important;
}

/* 行标题和列标题边框 */
:deep(.handsontable .ht_clone_top .htCore th),
:deep(.handsontable .ht_clone_left .htCore th),
:deep(.handsontable .ht_clone_corner .htCore th) {
  border-color: #DCDFE6 !important;
}

/* 选中单元格边框 */
:deep(.handsontable .htCore .current) {
  border-color: #0067D1 !important;
}

/* 焦点单元格边框 */
:deep(.handsontable .htCore .current.corner) {
  border-color: #0067D1 !important;
}

/* 字体颜色 */
:deep(.handsontable .htCore th),
:deep(.handsontable .htCore td) {
  color: #191919 !important;
}

/* 表头左对齐 */
:deep(.handsontable .htCore th) {
  text-align: left !important;
  cursor: pointer !important;
  transition: background-color 0.2s ease !important;
}

:deep(.handsontable .htCore th:hover) {
  background-color: #f0f9ff !important;
}

/* 只读模式下的鼠标样式 */
:deep(.handsontable.readonly .htCore th),
:deep(.handsontable.readonly .htCore td) {
  cursor: default !important;
  user-select: none !important;
}

:deep(.handsontable.readonly .htCore th:hover) {
  background-color: transparent !important;
}

/* 占位符样式 */
:deep(.handsontable .htCore td:empty::before) {
  content: '请输入表格内容';
  color: #AEAEAE;
  font-style: italic;
  opacity: 0.7;
}

/* 对齐样式 */
:deep(.htCenter) {
  text-align: center !important;
}

:deep(.htLeft) {
  text-align: left !important;
}

:deep(.htRight) {
  text-align: right !important;
}

:deep(.htTop) {
  vertical-align: top !important;
}

:deep(.htMiddle) {
  vertical-align: middle !important;
}

:deep(.htBottom) {
  vertical-align: bottom !important;
}

/* 列宽度调整手柄样式 */
:deep(.handsontable .manualColumnResizer) {
  background-color: rgba(30, 64, 175, 0.1) !important;
  width: 2px !important;
  cursor: col-resize !important;
  transition: all 0.2s ease !important;
}

:deep(.handsontable .manualColumnResizer:hover) {
  background-color: rgba(30, 64, 175, 0.2) !important;
  width: 3px !important;
}

/* 拖动时的样式 */
:deep(.handsontable .manualColumnResizer.active) {
  background-color: rgba(30, 64, 175, 0.2) !important;
  width: 3px !important;
}

/* 右键菜单样式 */
:deep(.handsontable .htContextMenu) {
  border-radius: 4px !important;
  overflow: hidden !important;
}

:deep(.handsontable .htContextMenu .ht_master) {
  border-radius: 4px !important;
  overflow: hidden !important;
}

/* 所有菜单的通用样式 */
:deep(.htMenu) {
  border-radius: 4px !important;
  overflow: hidden !important;
}

/* 动态创建的输入框样式 */
input[type="text"] {
  border: 1px solid #0067D1 !important;
  outline: 1px solid #0067D1 !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  margin: 0 !important;
  font-family: inherit !important;
}

input[type="text"]:focus {
  border: 1px solid #0067D1 !important;
  outline: 1px solid #0067D1 !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  background-color: #ffffff !important;
}

input[type="text"]:hover {
  border: 1px solid #0067D1 !important;
  outline: 1px solid #0067D1 !important;
  border-radius: 0 !important;
  box-shadow: none !important;
}

/* Handsontable 单元格输入框样式 */
:deep(.handsontable .handsontableInput) {
  border: 1px solid #0067D1 !important;
  outline: none !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  margin: 0 !important;
  font-family: inherit !important;
  background-color: #ffffff !important;
}

:deep(.handsontable .handsontableInput:focus) {
  border: 1px solid #0067D1 !important;
  outline: none !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  background-color: #ffffff !important;
}

:deep(.handsontable .handsontableInput:hover) {
  border: 1px solid #0067D1 !important;
  outline: none !important;
  border-radius: 0 !important;
  box-shadow: none !important;
}
</style>
